package org.acghub.mtdb.util;

import java.io.*;

public final class FileOperation {
    @SuppressWarnings("all")
    private static File toFile(File base, String name) {
        File file = new File(base, name);
        file.getParentFile().mkdirs();
        if (!file.getParentFile().exists()) throw new RuntimeException("can not create dirs: " + file.getParent());
        return file;
    }

    public static boolean fparse(File path, String name, LineParser parser, String encoding) {
        File file = toFile(path, name);
        if (!file.exists()) return false;
        try (BufferedReader lnr = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
            for (String line; (line = lnr.readLine()) != null; )
                parser.parseLine(line);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    public static PrintStream fopen(File path, String name, String encoding) {
        try {
            return new PrintStream(new CachedFileOutputStream(toFile(path, name)), false, encoding);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
